package com.huitone.gddw.service.impl.worktable;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huitone.gddw.dao.entity.ParamtabRec;
import com.huitone.gddw.dao.entity.PrgDispatchNotify;
import com.huitone.gddw.dao.entity.PrgDispatchNotify.DispatchStatus;
import com.huitone.gddw.dao.entity.PrgDispatchNotify.NotifyType;
import com.huitone.gddw.dao.entity.PrgInfo;
import com.huitone.gddw.dao.worktable.paramconfigmanage.IParamtabRecDao;
import com.huitone.gddw.service.IParamtabRecService;
import com.huitone.gddw.service.IPrgDispatchNotifyService;
import com.huitone.gddw.service.IPrgInfoService;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 平台运行参数表修改记录 接口实现类
 * @author wuluodan
 *
 */
@Service
public class ParamtabRecService implements IParamtabRecService {

	@Autowired
	private IParamtabRecDao paramtabRecDao;
	
	@Autowired
	private IPrgInfoService prgInfoService;
	
	@Autowired
	private IPrgDispatchNotifyService prgDispatchNotifyService;
	
	@Override
	public void update(String paramtabId, String desc) {
		List<ParamtabRec> list = paramtabRecDao.getByParamtabId(paramtabId);
		if (list.isEmpty() || 0 == list.size()) {
			this.save(paramtabId, desc);
		} else {
			ParamtabRec entity = list.get(0);
			entity.setDesc(desc);
			this.update(entity);
		}
	}
	
	/**
	 * 更新
	 * @param entity ParamtabRec
	 */
	private void update(ParamtabRec entity) {
		entity.setModTime(new Date());
		entity.setModStaffId(SysLoginUtil.getLoginUserId());
		paramtabRecDao.updateByPrimaryKey(entity);
		
		addNotify(entity);
	}
	
	/**
	 * 根据参数ID和说明保存信息
	 * @param paramtabId 参数ID
	 * @param desc 说明
	 */
	private void save(String paramtabId, String desc) {
		ParamtabRec entity = new ParamtabRec();
		entity.setParamtabId(paramtabId);
		entity.setDesc(desc);
		this.save(entity);
	}
	
	/**
	 * 保存
	 * @param entity ParamtabRec
	 */
	private void save(ParamtabRec entity) {
		entity.setInsertTime(new Date());
		entity.setInsertStaffId(SysLoginUtil.getLoginUserId());
		entity.setModTime(entity.getInsertTime());
		entity.setModStaffId(entity.getInsertStaffId());
		paramtabRecDao.insertSelective(entity);

		addNotify(entity);
	}
	
	/**
	 * 添加參數調度信息
	 * @param entity
	 */
	private void addNotify(ParamtabRec entity) {
		List<PrgInfo> list = prgInfoService.getByParamtabId(entity.getParamtabId());
		PrgDispatchNotify prgDispatchNotify;
		for (PrgInfo prgInfo : list) {
			PrgDispatchNotify pdn = prgDispatchNotifyService.getLastByPrgId(prgInfo.getPrgId());
			if (pdn != null && !pdn.getDispatchStatus().equals(DispatchStatus.COMPLETED.getCode())) {
				continue;
			}
			prgDispatchNotify = new PrgDispatchNotify();
			prgDispatchNotify.setPrgId(prgInfo.getPrgId());
			prgDispatchNotify.setParamtabId(entity.getParamtabId());
			prgDispatchNotify.setNotifyType(NotifyType.OVERLOAD.getCode());
			prgDispatchNotifyService.save(prgDispatchNotify);
		}
	}
	
}
